<script setup lang="ts" name="RoleList">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Delete, Edit, Plus, Setting } from '@element-plus/icons-vue'
import type { Role, PageQueryParams } from '@/model/user-role-model'
import { getRoles, deleteRole } from '@/request/user-role-api'

// 导入组件
import RoleForm from './components/RoleForm.vue'
import RolePermissions from './components/RolePermissions.vue'

// 角色表格数据
const tableData = ref<Role[]>([])
const total = ref(0)
const loading = ref(false)

// 分页和搜索参数
const queryParams = reactive<PageQueryParams>({
  page: 1,
  page_size: 10,
  keyword: ''
})

// 获取角色列表
const fetchRoleList = async () => {
  loading.value = true
  try {
    const res = await getRoles(queryParams)
    if (res.code === 0) {
      // 判断返回的data是数组还是包含roles和total的对象
      if (Array.isArray(res.data)) {
        tableData.value = res.data
        total.value = res.total || 0
      } else if (res.data && 'roles' in res.data) {
        tableData.value = res.data.roles
        total.value = res.data.total || 0
      }
    } else {
      ElMessage.error(res.errorMsg || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表出错：', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 重置查询条件
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.page = 1
  fetchRoleList()
}

// 处理页码改变
const handleCurrentChange = (page: number) => {
  queryParams.page = page
  fetchRoleList()
}

// 处理每页数量改变
const handleSizeChange = (size: number) => {
  queryParams.page_size = size
  queryParams.page = 1
  fetchRoleList()
}

// 打开角色弹窗
const dialogVisible = ref(false)
const currentRole = ref<Role | null>(null)
const dialogTitle = ref('创建角色')

const openDialog = (role?: Role) => {
  if (role) {
    currentRole.value = { ...role }
    dialogTitle.value = '编辑角色'
  } else {
    currentRole.value = null
    dialogTitle.value = '创建角色'
  }
  dialogVisible.value = true
}

// 打开权限分配弹窗
const permissionsDialogVisible = ref(false)
const roleForPermissions = ref<Role | null>(null)

const openPermissionsDialog = (role: Role) => {
  roleForPermissions.value = { ...role }
  permissionsDialogVisible.value = true
}

// 删除角色
const handleDelete = (role: Role) => {
  ElMessageBox.confirm(`确定要删除角色"${role.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteRole(role.id)
      if (res.code === 0) {
        ElMessage.success('删除成功')
        fetchRoleList()
      } else {
        ElMessage.error(res.errorMsg || '删除失败')
      }
    } catch (error) {
      console.error('删除角色出错：', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除，不做操作
  })
}

// 角色保存回调
const handleRoleSaved = () => {
  dialogVisible.value = false
  fetchRoleList()
}

// 权限分配回调
const handlePermissionsUpdated = () => {
  permissionsDialogVisible.value = false
  fetchRoleList()
}

// 计算权限数量（兼容不同返回字段）
const permissionCount = (role: Role) => {
  return role.permission_count ?? (role.permission_ids?.length ?? (role.permissions?.length ?? 0))
}

onMounted(() => {
  fetchRoleList()
})
</script>

<template>
  <div class="role-list-container p-4">
    <el-card class="box-card">
      <template #header>
        <div class="card-header flex items-center justify-between">
          <h2 class="text-xl font-bold">角色管理</h2>
          <el-button type="primary" :icon="Plus" @click="openDialog()">新增角色</el-button>
        </div>
      </template>
    
      <!-- 搜索区域 -->
      <div class="search-container mb-4 flex flex-wrap items-center gap-4">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入角色名称"
          clearable
          class="w-80"
          @keyup.enter="fetchRoleList"
          @clear="fetchRoleList"
        />
        <el-button type="primary" :icon="Search" @click="fetchRoleList">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </div>

      <!-- 角色表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="200" show-overflow-tooltip />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="权限数" width="100">
          <template #default="{ row }">
            {{ permissionCount(row) }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" show-overflow-tooltip />
        <el-table-column prop="updated_at" label="更新时间" width="180" show-overflow-tooltip />
        <el-table-column label="操作" fixed="right" width="250">
          <template #default="{ row }">
            <el-button type="primary" link :icon="Edit" @click="openDialog(row)">
              编辑
            </el-button>
            <el-button type="primary" link :icon="Setting" @click="openPermissionsDialog(row)">
              分配权限
            </el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container mt-4 flex justify-end">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.page_size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色表单弹窗 -->
    <RoleForm
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      :role="currentRole"
      @saved="handleRoleSaved"
    />
    
    <!-- 权限分配弹窗 -->
    <RolePermissions
      v-model:visible="permissionsDialogVisible"
      :role="roleForPermissions"
      @updated="handlePermissionsUpdated"
    />
  </div>
</template>

<style scoped lang="scss">
.role-list-container {
  .pagination-container {
    padding: 10px 0;
  }
  
  .el-button.el-button--primary.is-link,
  .el-button.el-button--danger.is-link {
    padding: 0 6px;
    margin-right: 0;
  }
}
</style>
